package sns.dao;

import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import sns.bean.User;

public class UserDao extends HibernateDaoSupport{

	public void save(User user){
		getSession().save(user);
	}
	
	public void merge(User user){
		getSession().merge(user);
	}
	
	public void delete(User user){
		getSession().delete(user);
	}
	
	/**
	 * find the user by username
	 * 
	 * @param username
	 * @return
	 */
	public User findByUsername(String username){
		if(username==null){
			return null;
		}
		Query q = getSession().createQuery("select user from User as user where user.username = :username");
		q.setString("username", username);
		return (User) q.uniqueResult();
	}
	
	/**
	 * get user by its id
	 * 
	 * @param iduser
	 * @return
	 */
	public User findUserById(Long iduser){
		if(iduser==null){
			return null;
		}
		Query q = getSession().createQuery("select user from User as user where user.iduser = :iduser");
		q.setLong("iduser", iduser);
		return (User)q.uniqueResult();
	}
	
	/**
	 * get the recently n registered users
	 * 
	 * @param n
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<User> getNewUsers(int n){
		if(n<0){
			return null;
		}
		Query q = getSession().createQuery("select user from User as user order by user.regtime desc");
		q.setFirstResult(0);
		q.setMaxResults(n);
		return (List<User>)q.list();
	}
	
	/**
	 * query users by the query string
	 * 
	 * @param qstr
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<User> queryUser(String qstr){
		if(qstr==null){
			return null;
		}
		Query q = getSession().createQuery("select user from User as user where user.nickname like :qstr");
		q.setString("qstr", "%"+qstr+"%");
		return (List<User>)q.list();
	}
	
}
